package cn.smbms.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;

import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.dao.UserMapper;
import cn.smbms.pojo.Bill;
import cn.smbms.pojo.Provider;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.BillService;
import cn.smbms.service.ProviderService;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.service.impl.BillServiceImpl;
import cn.smbms.service.impl.ProviderServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/bill")
public class BillController extends BaseInitController {
	private Logger logger = Logger.getLogger(BillController.class);

	@Resource
	private BillService billService;
	@Resource
	private ProviderService providerService;

	/**
	 * 查询订单列表 模糊查询
	 * 
	 * @param queryProductName
	 * @param queryProviderId
	 * @param queryIsPayment
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/billLogin.html")
	public String Billlogin(@RequestParam(value = "queryProductName", required = false) String queryProductName,
			@RequestParam(value = "queryProviderId", required = false) String queryProviderId,
			@RequestParam(value = "queryIsPayment", required = false) String queryIsPayment,
			@RequestParam(value = "pageIndex", required = false) String pageIndex, Model model,
			HttpServletRequest request) throws Exception {
		System.err.println("Billlogin成功进来了=============");
		List<Provider> providerList = new ArrayList<Provider>();

		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		// 商品id
		int _queryProviderId = 0;
		// 是否购买
		int isPayment = 0;
		List<Bill> billList = new ArrayList<Bill>();
		Bill bill = new Bill();
		if (StringUtils.isNullOrEmpty(queryProductName)) {
			queryProductName = "";
		}
		if (queryProviderId != null && !queryProviderId.equals("")) {
			_queryProviderId = Integer.parseInt(queryProviderId);
		}
		if (StringUtils.isNullOrEmpty(queryIsPayment)) {
			queryIsPayment = "";
		}
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/provider/syerror.html";
			}
		}
		bill.setProductName(queryProductName);
		// 总数量（表）
		int totalCount = billService.getBillCount(queryProductName, _queryProviderId, isPayment);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		System.out.println(
				currentPageNo + " currentPageNo====================" + pageSize + "pageSize==========================");
		billList = billService.getBillList(queryProductName, _queryProviderId, isPayment, currentPageNo, pageSize);
		System.out.println(_queryProviderId + "==========_queryProviderId");
		providerList = providerService.getProviderById();
		model.addAttribute("providerList", providerList);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("billList", billList);
		model.addAttribute("queryProductName", queryProductName);
		model.addAttribute("queryProviderId", queryProviderId);
		model.addAttribute("queryIsPayment", queryIsPayment);

		return "billlist.jsp";
	}

	@RequestMapping(value = "/billadd.html", method = RequestMethod.GET)
	public String billAdd(@ModelAttribute Bill bill) {

		return "billadd.jsp";

	}

	/**
	 * 返回供应商列表回去
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getProviderList")
	@ResponseBody
	public Object getProviderList(Model model) {
		List<Provider> providerList = providerService.getProviderById();
		model.addAttribute("providerList", providerList);
		logger.debug("providerList.size()" + providerList.size());
		return JSONArray.toJSONString(providerList);

	}

	/**
	 * 添加商品信息
	 * 
	 * @param bill
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "billaddSave.html", method = RequestMethod.POST)
	public String billAddSave(Bill bill, HttpSession session) {
		bill.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		bill.setCreationDate(new Date());
		if (billService.add(bill)) {
			return "redirect:/bill/billLogin.html";
		}
		return "billadd.jsp";
	}

	/**
	 * 根据订单id获取用户信息
	 * 
	 * @param id
	 *            获取到的订单id
	 * @param model保存进模型数据中
	 * @return
	 */
	@RequestMapping(value = "/billmodify.html/{id}", method = RequestMethod.GET)
	public String modifyBill(@PathVariable String id, Model model) {
		Integer _id = Integer.valueOf(id);
		Bill bill = billService.getBillById(_id);
		List<Provider> providerList = providerService.getProviderById();
		model.addAttribute("providerList", providerList);
		model.addAttribute("bill", bill);
		return "billmodify.jsp";

	}

	 

	@RequestMapping(value = "/billModifySave.html", method = RequestMethod.POST)
	public String modifysave(@ModelAttribute("bill") Bill bill, HttpSession session, Model model) {
		bill.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		bill.setModifyDate(new Date());
		if (billService.modify(bill)) {
			return "redirect:/bill/billLogin.html";
		}
		return "error.jsp";
		
	}

	/**
	 * 查询用户名是否重复
	 * 
	 * @return
	 */
	@RequestMapping("/billCodeExit")
	@ResponseBody
	public String userCodeExit(@RequestParam String billCode) {
		logger.debug("billCodeExit userCode===============" + billCode);
		Bill bill = billService.selectBillsCodeExist(billCode);
		HashMap<String, String> resMap = new HashMap<String, String>();

		if (null != bill) {
			// 用户名已存在
			resMap.put("billCode", "exist");
		} else {
			// 用户名可用
			resMap.put("billCode", "notexist");
		}
		return JSONArray.toJSONString(resMap);

	}

	/**
	 * 查看视图
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/viewAiax")
	@ResponseBody
	public Object viewAjax(@RequestParam String id/* ,Model model */) {
		logger.debug("viewAjax id==============================" + id);
		Integer _id = Integer.valueOf(id);
		Bill bill = billService.getBillById(_id);
		return bill;
	}

}
